package com.fire.communication.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.fire.communication.common.base.BaseService;
import com.fire.communication.common.utils.RedisUtil;
import com.fire.communication.common.utils.appkit.ConfigKit;
import com.fire.communication.config.websocket.SocketIOService;
import com.fire.communication.model.CommunicationRecord;
import com.fire.communication.model.DeviceBusiness;
import com.fire.communication.model.DictChild;
import com.fire.communication.model.NameAndPhone;
import com.fire.communication.model.margin.SmsVoiceMargin;
import com.fire.communication.support.model.RespEntity;
import com.fire.communication.support.mybatisplus.QueryWrapper;
import com.fire.communication.support.utils.MyLogger;
import com.fire.communication.support.utils.requestutil.HttpRequestUtil;
import com.fire.communication.web.mapper.CommunicationRecordMapper;
import com.fire.communication.web.mapper.DeviceBusinessMapper;
import com.fire.communication.web.mapper.DictChildMapper;
import com.fire.communication.web.mapper.SendMsgStateMapper;
import com.fire.communication.web.mapper.margin.SmsVoiceMarginMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;


/**
 * @author Yang yu
 * @version 1.0
 * @date 2020/7/23 15:33
 */
@Service
public class CommunicationService extends BaseService {

    @Resource
    public MyLogger logger;

    @Resource
    private DictChildMapper dictChildMapper;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    SocketIOService socketIOService;
    @Resource
    private CommunicationRecordMapper communicationRecordMapper;
    /**
     * 通知模块
     *
     * @param jsonParam
     * @return
     */
    public RespEntity communication(JSONObject jsonParam) throws Exception {//dataType= 1 报警  2  平时数据

        logger.info("---------------------------communication-----" + jsonParam.toString());

        //number不能为空  设备编号
        if (!jsonParam.containsKey("number") || jsonParam.getStr("number") == null || StrUtil.isBlank(jsonParam.getStr("number"))) {
            return RespEntity.fail("设备号不能为空!");
        }
        String alarmType = "";//最终形成的报警类型id
        String alarmTypePName = "";//最终形成的报警类型中文
        String deviceClassName = "";//设备分类中文
        //获取设备信息
        List<DeviceBusiness> deviceDetailList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceDetailList.isEmpty()) {
            return RespEntity.fail("设备号不存在!");
        }
        DeviceBusiness deviceDetail = deviceDetailList.get(0);//设备详情
        if (jsonParam.containsKey("dataType") && jsonParam.getStr("dataType") != null && StrUtil.isNotBlank(jsonParam.getStr("dataType"))) {
            //websocket连接，发送实时数据到大数据模块
            String socketStr = "number=" + jsonParam.getStr("number") +
                    ",lon=" + deviceDetail.getLon() +
                    ",lat=" + deviceDetail.getLat() +
                    ",deviceClassify=" + deviceDetail.getDeviceClassify() +
                    ",notificationType=1,alarmId=" + ",dataType=2";
            logger.info("---------------------------socketStr-----" + socketStr);
            //webSocket.sendMessageTo(socketStr);
            socketIOService.pushMessageToUser(socketStr);
            return RespEntity.success();
        }
        //接收到的报警类型中文：为逗号分隔的字符串
        String alarmTypeName = jsonParam.getStr("alarmTypeName");
        LinkedHashSet<String> alarmTypeList = new LinkedHashSet<>();
        LinkedHashSet<String> alarmTypeNameList = new LinkedHashSet<>();
        if (!alarmTypeName.isEmpty()) {//查询逗号分隔每项对应的大类
            List<String> names = getStrs(alarmTypeName);//去重
            for (String name : names) {
                QueryWrapper<DictChild> queryWrapper = new QueryWrapper();
                queryWrapper.eq("name", name);
                DictChild dictChild = dictChildMapper.selectOne(queryWrapper);
                if (!alarmTypeList.contains(dictChild.getPid()))
                    alarmTypeList.add(dictChild.getPid());//去重，因为小项对应的大项可能一样
                if (!alarmTypeNameList.contains(dictChild.getPidname()))
                    alarmTypeNameList.add(dictChild.getPidname());//去重，因为小项对应的大项可能一样
            }
            alarmType = String.join(",", alarmTypeList);
            alarmTypePName = String.join(",", alarmTypeNameList);
        } else {
            return RespEntity.fail("报警类型不能为空");
        }
        //rest请求单位详情接口，获取单位信息
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("id", deviceDetail.getBusinessId());
        com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "businessDetail", "alarmInfo");
        //当interfaceType为1时,为设备报警
        if ("1".equals(jsonParam.getStr("interfaceType"))) {

            jsonParam.put("alarmType", alarmType);
            jsonParam.put("alarmTypeName", alarmTypePName);
            logger.info("---------------------------alarmAdd-----" + jsonParam.toString());
            //添加日志
            String alarmId = alarmAdd(jsonParam, "firefightingiot_data", "alarmInfo", "alarmInfo");
            //websocket连接，发送报警信息
            String socketStr = "number=" + jsonParam.getStr("number") +
                    ",lon=" + deviceDetail.getLon() +
                    ",lat=" + deviceDetail.getLat() +
                    ",dataType=1" +
                    ",deviceClassify=" + deviceDetail.getDeviceClassify() +
                    ",notificationType=1,alarmId=" + alarmId;
            logger.info("---------------------------socketStr-----" + socketStr);
            //webSocket.sendMessageTo(socketStr);
            socketIOService.pushMessageToUser(socketStr);
        } else if ("2".equals(jsonParam.getStr("interfaceType"))) {//报警消除

        }
        return RespEntity.success();
    }

    //逗号分隔的字符串去重
    public List<String> getStrs(String alarmTypeName) {
        String[] names = alarmTypeName.split(",");
        List<String> list = new ArrayList<>();
        for (String str : names) {
            if (StrUtil.isNotBlank(str) && !list.contains(str.trim())) {
                list.add(str.trim());
            }
        }
        return list;
    }

    //获取单位表的负责人及电话 和设备表的报警电话
    public ArrayList<NameAndPhone> getList(com.alibaba.fastjson.JSONObject businessDetail, DeviceBusiness deviceDetail) {
        ArrayList<NameAndPhone> arrayList = new ArrayList();
        //单位表的负责人
        NameAndPhone nameAndPhone = new NameAndPhone();
        String oneResponPersonName = businessDetail.getString("oneResponPersonName");
        String oneResponPersonPhone = businessDetail.getString("oneResponPersonPhone");
        nameAndPhone = new NameAndPhone();
        nameAndPhone.setName(oneResponPersonName);
        nameAndPhone.setPhone(oneResponPersonPhone);
        arrayList.add(nameAndPhone);
//        String safeResponPersonName = businessDetail.getString("safeResponPersonName");
//        String safeResponPersonPhone = businessDetail.getString("safeResponPersonPhone");
//        nameAndPhone = new NameAndPhone();
//        nameAndPhone.setName(safeResponPersonName);
//        nameAndPhone.setPhone(safeResponPersonPhone);
//        arrayList.add(nameAndPhone);
        String safeManagePersonName = businessDetail.getString("safeManagePersonName");
        String safeManagePersonPhone = businessDetail.getString("safeManagePersonPhone");
        if (safeManagePersonPhone != null && StrUtil.isNotBlank(safeManagePersonPhone) && !safeManagePersonPhone.equals("null")) {
            if (safeManagePersonName != null && StrUtil.isNotBlank(safeManagePersonName) && !safeManagePersonName.equals("null")) {
                nameAndPhone = new NameAndPhone();
                nameAndPhone.setName(safeManagePersonName);
                nameAndPhone.setPhone(safeManagePersonPhone);
                arrayList.add(nameAndPhone);
            }
        }
        //设备表的报警电话
        String alarmPhone = deviceDetail.getAlarmPhone();
        if (alarmPhone != null && StrUtil.isNotBlank(alarmPhone) && !alarmPhone.equals("null")) {
            String[] split = alarmPhone.split(",");
            for (String phone : split) {
                nameAndPhone = new NameAndPhone();
                nameAndPhone.setName("报警负责人");
                nameAndPhone.setPhone(phone);
                arrayList.add(nameAndPhone);
            }
        }
        //自定义管理员
        if (businessDetail.containsKey("businessCustomizeManagePersonList")) {
            JSONArray jsonArray = businessDetail.getJSONArray("businessCustomizeManagePersonList");
            for (Object obj : jsonArray) {
                com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) obj;
                nameAndPhone = new NameAndPhone();
                nameAndPhone.setName(jsonObject.getString("personName"));
                nameAndPhone.setPhone(jsonObject.getString("personPhone"));
                arrayList.add(nameAndPhone);
            }
        }
//        //获取监管人员列表
//        JSON checkmanagePersonObject = makeDataForJSON(new JSONObject(),"businessJava","config","getCheckmanagePersonList","alarmInfo");
//        JSONArray jsonArray = (JSONArray)checkmanagePersonObject;
//        for(Object oo : jsonArray){
//            com.alibaba.fastjson.JSONObject checkmanagePerson = (com.alibaba.fastjson.JSONObject)oo;
//            nameAndPhone = new NameAndPhone();
//            nameAndPhone.setName(checkmanagePerson.getString("personName"));
//            nameAndPhone.setPhone(checkmanagePerson.getString("personPhone"));
//            arrayList.add(nameAndPhone);
//        }
        return arrayList;
    }



    /**
     * @Author YangYu
     * @Description 更新短信、语音状态（云智信）
     * @Date Created in 16:29 2022/7/12
     * @Param [jsonParam]
     */
    public RespEntity updateStateYZX(JSONObject jsonParam) throws IOException {
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetupJava", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (userType.equals("1")) {
            businessId = jsonParam.getStr("businessId");
        } else {
            jsonParam.put("businessId", homeId);
        }
        //TODO异步处理
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 阿里云更新短信/语音状态
     * @Date Created in 14:22 2023/5/30
     * @Param [jsonArray, type]
     */

    public void updateStateAliyun(JSONArray jsonArray, String type) throws IOException {

        List<CommunicationRecord> communicationRecordList2 = new ArrayList<>();
        List<CommunicationRecord> communicationRecordList3 = new ArrayList<>();
        CommunicationRecord communicationRecord = new CommunicationRecord();
        for (Object obj : jsonArray) {
            Map<String, Object> map = (Map<String, Object>) obj;
            JSONObject jsonObject = new JSONObject(map);
            if (type.equals("1")) {
                communicationRecord.setId(jsonObject.getStr("biz_id"));
                if (jsonObject.getBool("success")) {
                    communicationRecordList2.add(communicationRecord);
                } else {
                    communicationRecordList3.add(communicationRecord);
                }
            } else {
                communicationRecord.setId(jsonObject.getStr("call_id"));
                if (jsonObject.getStr("status_code").equals("200000")) {
                    communicationRecordList2.add(communicationRecord);
                } else {
                    communicationRecordList3.add(communicationRecord);
                }
            }
        }
        if (communicationRecordList2.size() > 0) {
            communicationRecordMapper.batchUpdate(communicationRecordList2, 2);
        }
        if (communicationRecordList3.size() > 0) {
            communicationRecordMapper.batchUpdate(communicationRecordList3, 3);
        }
    }
}
